package com.zoro.barn.commons.db.autopage;

import com.zoro.barn.commons.db.annotations.MybatisMapper;
import com.zoro.barn.commons.db.annotations.NeedPage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;

/**
 * @author zhaoxingwu
 */
class PageInitBean implements ApplicationRunner, ApplicationContextAware {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    private ApplicationContext applicationContext;
    @Override
    public void run(ApplicationArguments args) throws Exception {
        Map<String, Object> mapperMap = applicationContext.getBeansWithAnnotation(MybatisMapper.class);
        Collection<Object> beans = mapperMap.values();
        if (beans.isEmpty()) {
            BarnPagePlugin.setCanAdd();
            return;
        }
        boolean isInfoEnable = logger.isInfoEnabled();
        for (Object bean : beans) {
            Class<?> clazz = bean.getClass();
            Class<?>[] interfaces = clazz.getInterfaces();
            if (interfaces.length == 0) {
                continue;
            }
            for (Class<?> i : interfaces) {
                if (i.getAnnotation(MybatisMapper.class) == null) {
                    continue;
                }
                if (isInfoEnable) {
                    logger.info("find mapper ,class : {}", i);
                }
                Method[] methods = i.getDeclaredMethods();
                if (methods.length == 0) {
                    continue;
                }
                for (Method m : methods) {
                    if (m.getAnnotation(NeedPage.class) != null) {
                        String id = i.getName() + "." + m.getName();
                        if (isInfoEnable) {
                            logger.info("find mapper id : {}", id);
                        }
                        BarnPagePlugin.addNeedPageId(id);
                    }
                }
            }
        }
        BarnPagePlugin.setCanAdd();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
